#include <windows.h>
#include <string.h>
#include <strsafe.h>

 #include <locale.h>
 #include <stdlib.h>
 #include <wchar.h>
 
#include "Loader.h"
#include "screen.h"

#pragma warning(disable : 4995)
#pragma warning(disable : 4996)

Loader::Loader(const TCHAR *newExtension)
{
	StringCchCopy(Extension, MAX_PATH, newExtension);
	fileCount = 0;
}
int Loader::getUserChoise()
{
	if (fileCount > 0)
		return screen::menu(ExtensionFiles,fileCount,0,"Select Data File",5);
	else
		return -1;

return 0;
}
void Loader::findExtensionFiles()
{

   WIN32_FIND_DATA FindFileData;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   TCHAR DirSpec[MAX_PATH];  // directory specification
   char *filename;
   DWORD dwError;

   GetCurrentDirectory(MAX_PATH,DirSpec);

   StringCchCat(DirSpec, MAX_PATH, TEXT("\\\\*."));
   StringCchCat(DirSpec, MAX_PATH, Extension);
 
   hFind = FindFirstFile(DirSpec, &FindFileData);
   
   if (hFind == INVALID_HANDLE_VALUE) 
      return ;
   else 
   {
		 filename = wchar_to_locale(FindFileData.cFileName);
		 fileCount++;
		 ExtensionFiles[fileCount-1] = new char[1+(int)strlen(filename)];
		 strcpy(ExtensionFiles[fileCount-1],filename);
		 delete []filename;

      while (FindNextFile(hFind, &FindFileData) != 0) 
      {
		 filename = wchar_to_locale(FindFileData.cFileName);
		 fileCount++;
		 ExtensionFiles[fileCount-1] = new char[1+(int)strlen(filename)];
		 strcpy(ExtensionFiles[fileCount-1],filename);
		 delete []filename;
      }
    
      dwError = GetLastError();
      FindClose(hFind);
      if (dwError != ERROR_NO_MORE_FILES) 
         return;
   }


}
Loader::~Loader()
{
	for(int i=0;i<fileCount;i++)
		delete ExtensionFiles[i];
}


char * Loader::wchar_to_locale(wchar_t * str)
 {
	char * ptr;
	size_t s;
 
	/* first arg == NULL means 'calculate needed space' */
	s = wcstombs(NULL, str, 0);
 
	/* a size of -1 means there are characters that could not
	   be converted to current locale */
	if (s == -1)
		return NULL;
 
	/* malloc the necessary space */
	if ((ptr = (char *)malloc(s + 1)) == NULL)
		return NULL;
 
	/* really do it */
	wcstombs(ptr, str, s);
 
	/* ensure NULL-termination */
	ptr[s] = '\0';
 
	/* remember to free() ptr when done */
	return ptr;
 }
